import Vue from 'vue'
import VueRouter from 'vue-router'
import Index from '../views/index.vue'
import Login from '../views/login.vue'
import Home from '../views/home.vue'
import Goods from '../views/goods.vue'
import User from '../views/user.vue'
import Welcome from '../views/welcome.vue'

// 表示启用vue-router插件
Vue.use(VueRouter)

// 表示一个路由配置规则数组，里面包含各种路由规则配置对象
const routes = [
  {
    path: '/',
    name: 'Home',
    component: Home,
    redirect: { name: 'Welcome' },
    children: [
      {
        path: '',
        name: 'Welcome',
        component: Welcome
      },
      {
        path: 'goods',
        name: 'Goods',
        component: Goods
      },
      {
        path: 'user',
        name: 'User',
        component: User
      }
    ]
  },
  // 第一条路由规则配置对象
  {
    path: '/index',
    name: 'Index',
    component: Index
  },
  {

    path: '/login',
    name: 'Login',
    component: Login
  },
  {
    path: '/mine',
    name: 'Mine',
    // 开启路由组件懒加载,当你访问这条路由规则时,才会加载该文件 里面的注释表示打包后的js文件名
    component: () => import(/* webpackChunkName: "mine" */ '../views/mine.vue'),
    children: [
      {
        // path 不要加 /
        // 到时候下面的这个嵌套规则,会拼接成: /mine/detail/:song
        path: 'detail/:song',
        name: 'Detail',
        component: () => import(/* webpackChunkName: "detail" */ '../views/detail.vue')
      }
    ]
  },
  // {
  //   // 通过在路径后面添加 /:参数名 来定义路由参数
  //   path: '/detail/:song',
  //   name: 'Detail',
  //   component: () => import(/* webpackChunkName: "detail" */ '../views/detail.vue')
  // },
  {
    path: '/404',
    name: 'NotFound',
    component: () => import(/* webpackChunkName: "notfound" */ '../views/notfound.vue')
  },
  {
  // 不满足上面规则的所有规则
    path: '*',

    // 重定向
    // redirect: '/404'
    redirect: { name: 'NotFound' }
  }
]

// 里面上面的路由规则,创建一个路由对象
const router = new VueRouter({
  routes
})

router.beforeEach((to, from, next) => {
  console.log('路由守卫执行了')
  const token = localStorage.getItem('token') || ''
  // 如果访问的不是Login 并且 还没有登录， 这种情况你能跳转到login
  if (to.name !== 'Login' && !token) next({ name: 'Login' })
  // 否则你就可以正常访问
  else next()
})

export default router
